package cn.tedu.movie.controller;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateUtil;
import cn.tedu.movie.entity.OrderCancel;
import cn.tedu.movie.entity.OrderInsert;
import cn.tedu.movie.mapper.OrderMapper;
import cn.tedu.movie.mapper.SeatMapper;
import cn.tedu.movie.util.Utils;
import io.netty.util.HashedWheelTimer;
import io.netty.util.Timeout;
import io.netty.util.Timer;
import io.netty.util.TimerTask;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.rmi.CORBA.Util;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.time.LocalDate;
import java.util.Date;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/order/")
public class OrderAndSeatController {
    @Autowired(required = false)
    OrderMapper orderMapper;
    @Autowired(required = false)
    SeatMapper seatMapper;
    @PostMapping("insertOrder")
    @Transactional
    public int insertOrder(HttpServletRequest request, HttpSession session) {
        Integer totalPrice = Integer.parseInt(request.getParameter("totalPrice"));
        Integer sessionId = Integer.parseInt(request.getParameter("sessionId"));
        String[] seatNos = request.getParameterValues("seatNo");
        Date date = new Date();
        for (String seatNo : seatNos) {
            if (seatMapper.checkSeat(sessionId,seatNo)!=0){
                return -1;
            }
        }
        String code=createOrderId();
        OrderInsert order = new OrderInsert();
        order.setUserId(1);
        order.setCode(code);
        order.setTotalPrice(totalPrice);
        order.setSessionId(sessionId);
        order.setStatusId(0);
        order.setCreatedDate(date);
        order.setCancelDate(DateUtil.offset(date, DateField.SECOND, 30));
        int num = orderMapper.insertOrder(order);
        int id=orderMapper.selectByCode(code);
        for (String seatNo : seatNos) {
            seatMapper.insert(id,seatNo);
        }
        return id;
    }

    @GetMapping("success")
    public int update(HttpServletRequest request, HttpServletResponse response){
        String code=request.getParameter("out_trade_no");
        int id= orderMapper.selectByCode(code);
        Thread t= Utils.getThreadByName(id+"");
        int num=orderMapper.update(id);
        t.resume();

        try {
            response.sendRedirect("/order.html");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return num;
    }
    //生成唯一编码
    public static String createOrderId() {
        int machineId = 1;//最大支持1-9个集群机器部署
        int hashCodeV = UUID.randomUUID().toString().hashCode();
        if(hashCodeV < 0) {//有可能是负数
            hashCodeV = - hashCodeV;
        }
        // 0 代表前面补充0
        // 4 代表长度为4
        // d 代表参数为正数型
        return machineId+String.format("%010d", hashCodeV);
    }
    @RequestMapping("cancel")
    public void cancel(Integer id,Date date) {
        MyTimerTask timerTask = new MyTimerTask(id,30);
        Thread t=new Thread(timerTask,""+id);
        t.start();
    }
    @GetMapping("cancelOrder")
    OrderCancel orderCancel(Integer id){
        return orderMapper.orderCancel(id);
    }
    class MyTimerTask implements Runnable{
        private int id;
        private int time;
        public MyTimerTask( int id,int time) {
            this.id = id;
            this.time=time;
        }

        public void run() {
          Date date=  OrderAndSeatController.this.
                  orderMapper.orderCancel(id).getCancelDate();
            for (int i = 0; i < time*1; i++) {
                if ((date.getTime()-new Date().getTime())<=0){
                    break;
                }
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            Integer or=orderMapper.selectStatusById(id);
            if (or != 1) {
                OrderAndSeatController.this.orderMapper.deleteOrderById(id);
                OrderAndSeatController.this.seatMapper.deleteSeatByOrderId(id);
            }
        }
    }
}
